<template>
	<view class="merchantInto">
	    <view class="line">
			<view class="left">
				<text class="txt">店铺名称</text>
			</view>
			<view class="right">
				<input type="text" v-model="formData.merchant_name"  value="" placeholder="请输入商店名称" />
			</view>
		</view>
        <view class="line">
        	<view class="left">
        		<text class="txt">联系人</text>
        	</view>
        	<view class="right">
        		<input type="text" v-model="formData.proposer_name"  value="" placeholder="请输入联系人姓名" />
        	</view>
        </view>
        <view class="line">
        	<view class="left">
        		<text class="txt">手机号</text>
        	</view>
        	<view class="right">
        		<input type="number" v-model="formData.proposer_mobile" value="" placeholder="请输入手机号码" />
        	</view>
        </view>
		<view class="line jt">
			<view class="left">
				<text class="txt">店铺位置</text>
			</view>
			<view class="right">
				<view class="bottom1" @click="getMapLocation()">{{formData.latitude == '' ? '选择定位' : '重新选择定位'}}</view>
			</view>
		</view>
		<view class="line">
			<view class="left">
				<textarea class="textarea" v-model="formData.address" value="" placeholder=" 请填写详细地址，不少于5个字" />
			</view>
		</view>
		<view class="line">
			<view class="left">
				<text class="txt">营业执照</text>
			</view>
		</view>
		<view class="photos">
			<image :src="formData.codeImg != '' ? formData.codeImg : 'https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png'" mode="aspectFill" @click="chooseImage(0)"></image>
		</view>
		<view class="line" style="border-top: 1rpx #ebebeb solid;">
			<view class="left">
				<text class="txt">门店照</text>
			</view>
		</view>
		<view class="photos">
		    <view class="photo_list" v-for="(uploadItem,index) in formData.coversList" :key="index">
		        <image :src="uploadItem.thumbUrl" mode="aspectFill" @tap="previewImage"
		            :data-src="uploadItem.imgUrl" :data-id="index"></image>
		        <image @click="delImg(index)"
		            src="https://hdsq.aoorange.cn/attachment/xcx/icon/del-new.png" class="del"
		            mode="aspectFill"></image>
		    </view>
		    <image src="https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png" mode="aspectFill"
		        @click="chooseImage(1)"></image>
			<!-- <shmily-drag-image :list.sync="coversList" imageWidth="200"></shmily-drag-image> -->
		</view>
		<view class="heng"></view>
		<view class="line">
			<view class="left">
				<text class="txt">业务员</text>
			</view>
			<view class="right">
				{{business.username + "("+business.mobile+")"}}
			</view>
		</view>
		<view class="heng"></view>
		<view class="deal">
			<view :class="isclick?'sel':'nosel'" @click="isclick = !isclick"></view>
			<text @click="isclick = !isclick">已阅读，并同意</text>
			<text @click="jump('applyAgreement', 'batch_explain')">《批发商协议》</text>
		</view>
		<view class="bottom" @click="save">申请批发商</view>
	</view>
</template>

<script>
	var _self;
	import serve from '../static/request.js';
	import storage from '../static/appkey.js';
	import common from '../static/jump.js';
	export default {
		data() {
			return {
				formData: {
					appkey: uni.getStorageSync('appkey'),
					'access-token': uni.getStorageSync('access-token'),
					merchant_name : '',
					proposer_name: '',
					proposer_mobile: '',
					address: '',
					address_name: '',
					longitude: '',
					latitude: '',
					bid: 0,
					wechatCode: '',
					codeImg: '',
					codePath: '',
					coversList: '',
					covers: '',
				},
				business:{
					username: '',
					mobile : '',
				},
				isSubmit: false,
				isclick: false,
				isLoad: false,
				codeUrl: '',
				coversList: [],
				imgList: [],
			}
		},
		methods: {
			getMapLocation(){
				_self.isLoad = true;
				uni.chooseLocation({
					'longitude': _self.formData.longitude,
					'latitude': _self.formData.latitude,
					success:(res)=> {
						console.info(res);
						_self.formData.address = res.name;
						_self.formData.longitude = res.longitude;
						_self.formData.latitude = res.latitude;
						_self.$forceUpdate();
						// this.getRegionFn(res);
					},
					fail:()=>{
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
						uni.getSetting({
							success: (res) => {
								var status = res.authSetting;
								if(!status['scope.userLocation']){
								// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
									uni.showModal({
										title:"是否授权当前位置",
										content:"需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success:(tip)=>{
											if(tip.confirm){
											// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
												uni.openSetting({
													success:(data)=>{
													// 如果用户授权了地理信息在，则提示授权成功
														if(data.authSetting['scope.userLocation']===true){
															uni.showToast({
																title:"授权成功",
																icon:"success",
																duration:1000
															})
															// 授权成功后，然后再次chooseLocation获取信息
															uni.chooseLocation({
																success: (res) => {
																	console.log("详细地址",res);
																	// this.getRegionFn(res);
																}
															})
														}else{
															uni.showToast({
																title:"授权失败",
																icon:"none",
																duration:1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title:"调用授权窗口失败",
									icon:"none",
									duration:1000
								})
							}
						})
					}
				});
			},
			getInfo() {
				serve.request({
					url: '/spread/batch/prepare',
					data: {
						appkey: uni.getStorageSync('appkey'),
						'access-token': uni.getStorageSync('access-token'),
						bid : _self.formData.bid
					}
				}).then(res => {
					if (res.code == 200) {
						_self.business.username = res.data.username;
						_self.business.mobile = res.data.mobile;
						_self.formData = res.data.applyInfo;
						_self.formData.appkey = uni.getStorageSync('appkey');
						_self.formData["access-token"] = uni.getStorageSync('access-token');
						let imgStr = '';
						if (_self.formData.coversList.length > 0) {
						    _self.formData.coversList.forEach((imgItem, imgKey) => {
						        _self.imgList[imgKey] = imgItem.imgUrl;
								imgStr += imgItem.imgPaht+';';
						    });
						}
						_self.formData.covers = imgStr;
						uni.setStorageSync('recommend_mobile', res.data.mobile);
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							success() {
								setTimeout(function() {
									console.info(111);
									common.jump('return_one');
								}, 2000)
							}
						});
					}
				});
			},
			
			async save() {
				if (_self.isSubmit) {//防止重复提交
					return;
				}
				if (!_self.isclick) {
					uni.showToast({
						title: "请同意协议",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.merchant_name == "") {
					uni.showToast({
						title: "请填写商铺名称",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.proposer_name == "") {
					uni.showToast({
						title: "请填写联系人",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.proposer_mobile == "") {
					uni.showToast({
						title: "请填写联系电话",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.longitude == "" || _self.formData.latitude == "") {
					uni.showToast({
						title: "请点击地图获取经纬度",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.address == "") {
					uni.showToast({
						title: "请填写详细地址",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.codeImg == "") {
					uni.showToast({
						title: "请上传营业执照",
						icon: 'none'
					})
					return;
				}
				if(_self.formData.codePath == '') {
					let uresult = await _self.uploadFileFun(_self.formData.codeImg);
					if (!uresult) {
					    uni.showToast({
					        title: "营业执照上传失败",
					        icon: 'none'
					    });
					    return;
					}
					_self.formData.codePath = uresult;
				}
				if(_self.formData.coversList.length == 0) {
					uni.showToast({
					    title: "请上传门店照片",
					    icon: 'none'
					});
					return;
				}
				let imgStr = '';
				for(let kk = 0; kk < _self.formData.coversList.length; kk ++) {
					let it = _self.formData.coversList[kk];
					if(it.isUpload == 0) {
						let uresult = await _self.uploadFileFun(it.imgUrl);
						if (!uresult) {
						    uni.showToast({
						        title: "门头照第" + (Number(kt) + Number(1)) +"张图片上传失败",
						        icon: 'none'
						    });
						    return;
						}
						it.imgPaht = uresult;
						it.isUpload = 1;
					}
					imgStr += it.imgPaht + ";";
				}
				_self.formData.covers = imgStr;
				// _self.formData["access-token"] = '';
				serve.request({
					url: '/spread/batch/apply',
					data: _self.formData
				}).then(res => {
					if (res.code == 200) {
						uni.setStorageSync('access-token', res.data["access-token"]);
						if(res.data.isConfim == 1) {
							let rechargeMoney = res.data.recharge;
							uni.showModal({
								title: '提示',
								content: res.message,
								showCancel:true,
								cancelText: '批发商城',
								confirmText:'去充值',
								success: function (res) {
									if (res.confirm) {
										uni.redirectTo({
											url: '/business/recharge?money='+rechargeMoney
										})
									} else if(res.cancel) {
										uni.redirectTo({
											url: '/pages/store/batch'
										})
									}
								}
							});
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
								success:function(){
									uni.redirectTo({
										url: '/pages/store/batch'
									})
								}
							});
							
						}
						
						return ;
					}
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
					uni.login({
						success: function (res) {
							_self.formData.wechatCode = res.code;
						},
						fail:function(){
							uni.showToast({
								title: '当前微信版本不支持，请升级',
								icon: 'none'
							});
						}
					});
					_self.isSubmit = false;
					
				});
				_self.isSubmit = true;
			},
			chooseImage(k) {
				_self.isLoad = true;
				let surplusNum = k == 0 ? 1 : 9;
			    uni.chooseImage({
			        count: surplusNum,
			        sizeType: ['original'],
			        sourceType: ['album'],
			        success: (chooseImageRes) => {
			            const tempFilePaths = chooseImageRes.tempFiles;
			            tempFilePaths.forEach((file, key) => {
			                const maxSize = 10 * 1024 * 1024;
			                // console.info("file.size = " + file.size);
			                if (file.size > maxSize) {
			                    uni.showToast({
			                        icon: "none",
			                        title: "文件不能大于10兆",
			                        mask: true,
			                        duration: 1.5e3
			                    });
			                    return;
			                } else {
								if(k == 0) {
									_self.formData.codePath = '';
									_self.formData.codeImg = file.path;
									return ;
								}
			                    let temp = {
									thumbUrl: file.path,
			                        imgUrl: file.path,
			                        isUpload: 0,
			                        imgPath: ''
			                    };
			                    _self.formData.coversList.push(temp);
			                    _self.imgList = [];
			                    _self.formData.coversList.forEach((it, kt) => {
			                        _self.imgList.push(it.imgUrl);
			                    });
			                }
			            });
			            _self.$forceUpdate();
			        }
			    });
			},
			previewImage: function(e) {
			    var current = e.target.dataset.src;
			    uni.previewImage({
			        current: current,
			        urls: _self.imgList
			    });
			    return;
			},
			delImg(key) {
			    _self.formData.coversList.splice(key, 1);
			    _self.imgList = [];
			    _self.formData.coversList.forEach((it, kt) => {
			        _self.imgList.push(it.imgUrl);
			    });
			    _self.$forceUpdate();
			},
			async uploadFileFun(file) {
			    let accessToken = uni.getStorageSync('access-token');
			    let appkey = uni.getStorageSync('appkey');
			    return new Promise((resolve, reject) => {
			        uni.uploadFile({
			            url: serve.apiUrl() + '/v1/file/images?appkey=' + appkey +
			                '&access-token=' + accessToken,
			            filePath: file,
			            name: 'file',
			            formData: {},
			            success: (uploadFileRes) => {
			                let result = JSON.parse(uploadFileRes.data);
			                console.info(result);
			                if (result.code == 200) {
			                    resolve(result.data.imgPath);
			                } else {
			                    resolve(false);
			                }
			            }
			        });
			    });
			},
			
			jump(jump_type, jump_link) {
				if(jump_type == 'applyAgreement') {
					if(uni.getStorageSync('access-token') == '') {
						common.jump('login');
					}
				}
				common.jump(jump_type, jump_link);
			}
		},
		onLoad(option) {
			_self = this;
			_self.formData.bid = option.bid;
			uni.login({
				success: function (res) {
					_self.formData.wechatCode = res.code;
				},
				fail:function(){
					uni.showToast({
						title: '当前微信版本不支持，请升级',
						icon: 'none'
					});
				}
			});
		},
		onShow() {
			if(_self.isLoad == false) {
				_self.getInfo();
			}
		},
		onPullDownRefresh() {
			console.log('refresh');
			setTimeout(function() {
				uni.stopPullDownRefresh(); //结束下拉加载状态
			}, 1000);
		}
	}
</script>

<style scoped lang="scss">
	.merchantInto{
		padding-bottom: 100upx;
		.main{
			width:100%;
			height:360upx;
		}
		.heng{
			width: 100%;
			height: 12upx;
			background: #F8F8FA;
		}
		.nobottom{
			border: none !important;
		}
		.deal{
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24upx;
			padding: 55upx 0upx;
			text:nth-child(2){
				color: #999999;
				margin-left: 11upx;
			}
			text:nth-child(3){
				color: #EB5938;
				margin-left: 11upx;
			}
			.sel {
				background-image: url(https://hdsq.aoorange.cn/attachment/xcx/icon/icon37.png);
				background-repeat: no-repeat;
				width:30upx;
				height:30upx;
				background-size: 100%;
				margin-right: 20upx;
			}
			
			.nosel {
				width: 30upx;
				height: 30upx;
				border: 1upx solid #999999;
				border-radius: 50%;
				margin-right: 20upx;
			}
		}
		.bottom{
			position: fixed;
			bottom: 0;
			width:100%;
			height:100upx;
			line-height: 100upx;
			text-align: center;
			color: #FFFFFF;
			font-size: 28upx;
			background:rgba(255,188,0,1);
			z-index: 9;
		}
		.title{
			color: #666666;
			font-size: 32upx;
			font-weight: bold;
			padding-top: 52upx;
			padding-left: 30upx;
		}
		.jt::after{
		position: absolute;
		right: 30upx;
		top: 60upx;
		content: '';
		border: 1upx solid rgba(57, 72, 107, 0.5);
		border-width: 0 3upx 3upx 0;
		padding: 6upx;
		transform: rotate(-45deg);
		-webkit-transform: rotate(-45deg);
		}
		.line{
			position: relative;
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				box-sizing: border-box;
				padding: 44upx 30upx;
				border-bottom: 1upx #EBEBEB solid;
				.left{
					display: flex;
					flex-direction: column;
					font-size: 32upx;
					.txt{
						color: #999999;
					}
					.txt1{
						color: #333333;
						font-size: 32upx;
					}
					.txt2{
						color: #999999;
						font-size: 24upx;
						margin-top: 10upx;
					}
					input{
						width: 690upx;
					}
					.textarea{
						border: 1px solid #ccc;
						width: 90vw;
						padding: 10rpx;
						height: 100rpx;
					}
				}
				.right{
					.bottom1{
						color: #e64545;
						margin-right: 20rpx;
					}
					
					input{
						// color: #CCCCCC;
						font-size: 32upx;
						text-align: right;
						border: 1rpx solid #ccc;
						height: 60rpx;
						padding-right: 10rpx;
					}
					.selPicker{
						padding: 0 10rpx;
						border: 1px solid #cccc;
						height: 80rpx;
						line-height: 80rpx;
						text-align: center;
						letter-spacing: 5rpx;
					}
					
					.region{
						font-size: 32upx;
						color:#333333;
						padding-right: 30upx;
					}
					.noregion{
						color:#CCCCCC;
						padding-right: 30upx;
					}
					.sel {
						background-image: url(https://hdsq.aoorange.cn/attachment/xcx/icon/xuanzhong.png);
						background-repeat: no-repeat;
						width: 40upx;
						height: 40upx;
						background-size: 100%;
						margin-right: 20upx;
					}
					
					.nosel {
						width: 36upx;
						height: 36upx;
						border: 1upx solid #999999;
						border-radius: 50%;
						margin-right: 20upx;
					}
				}
			}
		
	}
		.photos {
		    box-sizing: border-box;
		    padding: 30upx 30upx;
		    display: flex;
		    flex-wrap: wrap;
		
		    image {
		        width: 150upx;
		        height: 150upx;
		        border-radius: 10upx;
		        margin-bottom: 20upx;
		    }
		
		    .photo_list {
		        margin-right: 30upx;
		        padding-bottom: 20upx;
		        display: flex;
		        flex-direction: column;
		        align-items: flex-end;
		        position: relative;
		
		        view {
		            color: red;
		            font-size: 30upx;
		        }
		
		        .del {
		            width: 48upx !important;
		            position: absolute;
		            height: 48upx !important;
		            top: -24upx;
		            right: -24upx;
		        }
		    }
		}
</style>